package com.yumo.kangchenjunga;

import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.yumo.kangchenjunga.activity.Activity;
import com.yumo.kangchenjunga.activity.ActivityService;
import com.yumo.kangchenjunga.security.CustomUserDetails;

@Controller
public class LoginController {

	@Autowired
	private ActivityService activityService;

	@GetMapping("/admin/login")
	public String adminLogin() {
		return "login_admin";
	}

	@GetMapping("/company/login")
	public String companyLogin() {
		return "login_company";
	}

	@GetMapping("/company")
	public String company(@AuthenticationPrincipal CustomUserDetails user) {
		if (user.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_STORE_ADMIN")) ||
				user.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_STORE_USER"))) {
			return "forward:/company/coupons/validate";
		} else if (user.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_COMPANY_ADMIN")) ||
				user.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_COMPANY_USER"))) {
			return "forward:/company/users";
		}
		return "forward:/403";
	}

	@GetMapping("/admin")
	public String admin(@AuthenticationPrincipal CustomUserDetails user) {
		if (user.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_ADMIN"))
				|| user.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_POWER_USER"))
				|| user.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_USER"))) {
			return "forward:/admin/activities";
		}

		return "forward:/403";
	}

	@RequestMapping("/403")
	public String page403() {
		return "403";
	}

	@GetMapping("/test3")
	public String pageTest() {
		return "test";
	}

	@GetMapping("/activity")
	public String pageActivity(Model model) {
		model.addAttribute("search", new Activity());
		model.addAttribute("companies", new ArrayList<>());
		return "admin/activity";
	}

	@GetMapping({ "/test", "/test/obtainment" })
	public String pageTestObtain() {
		return "test/obtain";
	}

	@GetMapping("/test1")
	public String pageTest1() {
		return "test1";
	}

	@GetMapping("/test2")
	public String pageTest2(Model model) {
		model.addAttribute("activities", activityService.list());
		return "test2";
	}

}
